package com.css.zfzx.fxpg.modules.economicloss.middle.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.economicloss.middle.repository.entity.FxEconomyLossMiddleEntity;
import com.css.zfzx.fxpg.modules.economicloss.middle.service.FxEconomyLossMiddleService;
import com.css.zfzx.fxpg.modules.economicloss.middle.viewobjects.FxEconomyLossMiddleQueryParams;
import com.css.zfzx.fxpg.modules.economicloss.middle.viewobjects.FxEconomyLossMiddleVO;
import com.css.zfzx.fxpg.modules.economicloss.middle.repository.FxEconomyLossMiddleNativeRepository;
import com.css.zfzx.fxpg.modules.economicloss.middle.repository.FxEconomyLossMiddleRepository;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageImpl;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author andy
 * @date 2020-12-02
 */
@Service
@Slf4j
public class FxEconomyLossMiddleServiceImpl implements FxEconomyLossMiddleService {

	@Autowired
    private FxEconomyLossMiddleRepository fxEconomyLossMiddleRepository;
    @Autowired
    private FxEconomyLossMiddleNativeRepository fxEconomyLossMiddleNativeRepository;

    @Override
    public JSONObject queryFxEconomyLossMiddles(FxEconomyLossMiddleQueryParams queryParams, int curPage, int pageSize) {
        Page<FxEconomyLossMiddleEntity> fxEconomyLossMiddlePage = this.fxEconomyLossMiddleNativeRepository.queryFxEconomyLossMiddles(queryParams, curPage, pageSize);
        List<FxEconomyLossMiddleVO> fxEconomyLossMiddleVOList = new ArrayList<>();
        List<FxEconomyLossMiddleEntity> fxEconomyLossMiddleEntityList = fxEconomyLossMiddlePage.getContent();
        for(FxEconomyLossMiddleEntity fxEconomyLossMiddleEntity : fxEconomyLossMiddleEntityList){
            FxEconomyLossMiddleVO fxEconomyLossMiddleVO = new FxEconomyLossMiddleVO();
            BeanUtils.copyProperties(fxEconomyLossMiddleEntity, fxEconomyLossMiddleVO);
            if(PlatformObjectUtils.isNotEmpty(fxEconomyLossMiddleEntity.getDamageDegree())) {
                fxEconomyLossMiddleVO.setDamageDegreeName(findByDictCodeAndDictItemCode("damageDegree", fxEconomyLossMiddleEntity.getDamageDegree()));
            }
            if(PlatformObjectUtils.isNotEmpty(fxEconomyLossMiddleEntity.getEarthquakeIntensity())) {
                fxEconomyLossMiddleVO.setEarthquakeIntensityName(findByDictCodeAndDictItemCode("earthquakeIntensity", fxEconomyLossMiddleEntity.getEarthquakeIntensity()));
            }
            fxEconomyLossMiddleVOList.add(fxEconomyLossMiddleVO);
        }
        Page<FxEconomyLossMiddleVO> FxEconomyLossMiddleVOPage = new PageImpl(fxEconomyLossMiddleVOList, fxEconomyLossMiddlePage.getPageable(), fxEconomyLossMiddlePage.getTotalElements());
        JSONObject jsonObject = PlatformPageUtils.formatPageData(FxEconomyLossMiddleVOPage);
        return jsonObject;
    }


    @Override
    public FxEconomyLossMiddleEntity getFxEconomyLossMiddle(String id) {
        FxEconomyLossMiddleEntity fxEconomyLossMiddle = this.fxEconomyLossMiddleRepository.findById(id).orElse(null);
         return fxEconomyLossMiddle;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxEconomyLossMiddleEntity saveFxEconomyLossMiddle(FxEconomyLossMiddleEntity fxEconomyLossMiddle) {
        String uuid = UUIDGenerator.getUUID();
        fxEconomyLossMiddle.setId(uuid);
        fxEconomyLossMiddle.setCreateUser(PlatformSessionUtils.getUserId());
        fxEconomyLossMiddle.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        fxEconomyLossMiddle.setIsValid("1");
        this.fxEconomyLossMiddleRepository.save(fxEconomyLossMiddle);
        return fxEconomyLossMiddle;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxEconomyLossMiddleEntity updateFxEconomyLossMiddle(FxEconomyLossMiddleEntity fxEconomyLossMiddle) {
        fxEconomyLossMiddle.setUpdateUser(PlatformSessionUtils.getUserId());
        fxEconomyLossMiddle.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxEconomyLossMiddle.getId();
        FxEconomyLossMiddleEntity one = fxEconomyLossMiddleRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxEconomyLossMiddle, one);
        this.fxEconomyLossMiddleRepository.save(one);
        return fxEconomyLossMiddle;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxEconomyLossMiddles(List<String> ids) {
        List<FxEconomyLossMiddleEntity> fxEconomyLossMiddleList = this.fxEconomyLossMiddleRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(fxEconomyLossMiddleList) && fxEconomyLossMiddleList.size() > 0) {
            for(FxEconomyLossMiddleEntity fxEconomyLossMiddle : fxEconomyLossMiddleList) {
                this.fxEconomyLossMiddleRepository.delete(fxEconomyLossMiddle);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    public List<FxEconomyLossMiddleEntity> queryFxEconomyLossMiddles(FxEconomyLossMiddleQueryParams queryParams) {
        List<FxEconomyLossMiddleEntity> fxEconomyLossMiddles = this.fxEconomyLossMiddleNativeRepository.getFxEconomyLossMiddles(queryParams);
        return fxEconomyLossMiddles;
    }

    @Override
    public String exportExcel(FxEconomyLossMiddleQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxEconomyLossMiddleEntity> middleEntities = fxEconomyLossMiddleNativeRepository.getFxEconomyLossMiddles(queryParams);
            // 深拷贝
            ArrayList<FxEconomyLossMiddleVO> vos = new ArrayList<>();
            for (FxEconomyLossMiddleEntity middleEntity : middleEntities) {
                FxEconomyLossMiddleVO vo = new FxEconomyLossMiddleVO();
                BeanUtils.copyProperties(middleEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "经济损失风险评估-确定性损失区划", "经济损失风险评估-确定性损失区划", FxEconomyLossMiddleVO.class, "经济损失风险评估-确定性损失区划.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public String exportEstimateExcel(FxEconomyLossMiddleQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxEconomyLossMiddleEntity> middleEntities = fxEconomyLossMiddleNativeRepository.getFxEconomyLossMiddles(queryParams);
            // 深拷贝
            ArrayList<FxEconomyLossMiddleVO> vos = new ArrayList<>();
            for (FxEconomyLossMiddleEntity middleEntity : middleEntities) {
                FxEconomyLossMiddleVO vo = new FxEconomyLossMiddleVO();
                BeanUtils.copyProperties(middleEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "经济损失风险评估-损失估计计算", "经济损失风险评估-损失估计计算", FxEconomyLossMiddleVO.class, "经济损失风险评估-损失估计计算.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public String exportEconomyLossExcel(FxEconomyLossMiddleQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxEconomyLossMiddleEntity> middleEntities = fxEconomyLossMiddleNativeRepository.getFxEconomyLossMiddles(queryParams);
            // 深拷贝
            ArrayList<FxEconomyLossMiddleVO> vos = new ArrayList<>();
            for (FxEconomyLossMiddleEntity middleEntity : middleEntities) {
                FxEconomyLossMiddleVO vo = new FxEconomyLossMiddleVO();
                BeanUtils.copyProperties(middleEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "经济损失风险评估-中间结果管理", "经济损失风险评估-中间结果管理", FxEconomyLossMiddleVO.class, "经济损失风险评估-中间结果管理.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            //
            params.setTitleRows(1);
            // 设置解析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxEconomyLossMiddleVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxEconomyLossMiddleVO.class, params);
            List<FxEconomyLossMiddleVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxEconomyLossMiddleVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxEconomyLossMiddleVO EconomyLossMiddleVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + EconomyLossMiddleVO.getRowNum() + "行" + EconomyLossMiddleVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    private void saveExcel(List<FxEconomyLossMiddleVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxEconomyLossMiddleEntity EconomyLossMiddleEntity = new FxEconomyLossMiddleEntity();
            FxEconomyLossMiddleVO EconomyLossMiddleVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(EconomyLossMiddleVO, EconomyLossMiddleEntity);
            saveFxEconomyLossMiddle(EconomyLossMiddleEntity);
        }
    }
}
